﻿//基础设置 - 用户管理
layui.use(['form', 'jquery', 'laydate', 'dialog', 'table', 'laypage', 'ajaxUtil', 'permissionUtil', 'switchTab'], function () {
    var table = layui.table,
        laypage = layui.laypage,
        $ = layui.jquery,
        dialog = layui.dialog,
        ajaxutil = layui.ajaxUtil,
        laydate = layui.laydate,
        form = layui.form,
        permissionUtil = layui.permissionUtil,
        switchTab = layui.switchTab;
    permissionUtil.setting(160000);

    //表格渲染
    table.render({
        id: 'cn_GridBasicSetting'
        , elem: '#grid_BasicSetting'
        , method: 'post'
        , url: '/basicSetting/userinfo/list'
        //启动分页
        , page: true
        , height: 'full-100'
        , loading: true
        , text: { none: '未查询到数据' }
        , limit: 20
        , limits: [20, 50, 100]
        //禁用前端自动排序
        , autoSort: false
        , where: {
            operatorName: ''
        }
        , request: {
            pageName: 'pageIndex'
            , limitName: 'pageSize'
        }
        , response: {
            //statusName: 'status', //规定数据状态的字段名称，默认：code
            statusCode: 200, //规定成功的状态码，默认：0
            //msgName: 'hint', //规定状态信息的字段名称，默认：msg
            countName: 'total', //规定数据总数的字段名称，默认：count
            //dataName: 'rows' //规定数据列表的字段名称，默认：data
        }
        , cols: [[
            { field: 'operatorId', width: 80, title: '编号' }
            , { field: 'operatorNo', width: 150, title: '登录账号' }
            , { field: 'operatorName', width: 100, title: '真实姓名' }
            , { field: 'status', width: 100, title: '状态', templet: '#BasicSettingStatusCode' }
            , { field: 'createTime', width: 150, title: '创建时间' }
            , { fixed: 'right', title: '操作', toolbar: '#barOperation', width: 260 }
        ]]
    });

    //监听排序事件 
    table.on('sort(ft_BasicSetting)', function (obj) {
        if (obj.type !== null) {
            table.reload('cn_GridBasicSetting', {
                initSort: obj
                , where: {
                    sortName: obj.field //排序字段
                    , sortOrder: obj.type //排序方式
                    , operatorName: $('#txt_BasicIndex_OperatorName').val()
                }
            });
        }
    });

    //监听行工具事件
    table.on('tool(ft_BasicSetting)', function (obj) {
        var rowData = obj.data;
        if (obj.event === 'del') {
            var operatorId = rowData.operatorId;
            dialog.alert.confirm({
                message: '确定删除该用户吗？'
                , success: function (index) {
                    dialog.close(index);
                    ajaxutil.request({
                        url: '/basicSetting/userinfo/del',
                        data: {
                            operatorId: operatorId
                        },
                        success: function (res) {
                            if (res.code === 200) {
                                dialog.alert.msg('删除成功');

                                var pageIndex = $(".layui-laypage-skip").find("input").val();
                                //刷新页面
                                loadData({
                                    operatorName: $('#txt_BasicIndex_OperatorName').val()
                                }, pageIndex)
                            } else {
                                dialog.alert.fail(res.msg);
                            }
                        }
                    });
                }
            });
        }
        else if (obj.event === 'setRole') {
            getRoleInfo(rowData.operatorId);

            dialog.open({
                dialogId: 'dialog_BasicSetting_AllotRole'
                , width: 450
                , height: 360
                , title: '分配角色'
                , ok: function (index) {
                    allotRole(index, rowData.operatorId);
                }
                , cancel: function () {

                }
            });
        }
        else if (obj.event === 'reset') {
            $(".cs_BasicSettingNewOperatorPwd").val('');
            $(".cs_BasicSettingNewOperatorPwdAgain").val('');

            dialog.open({
                dialogId: 'dialog_BasicSetting_Reset'
                , width: 450
                , height: 260
                , title: '重置密码'
                , ok: function (index) {
                    resetPwd(index, rowData.operatorId);
                }
                , cancel: function () {

                }
            });
        }
        else if (obj.event === 'edit') {
            initEditForm(rowData);
            dialog.open({
                dialogId: 'dialog_BasicSetting_Edit'
                , width: 450
                , height: 200
                , title: '修改'
                , ok: function (index) {
                    editUser(index, rowData.operatorId);
                }
                , cancel: function () {

                }
            });
        }
    });

    //监听行状态
    form.on('switch(ft_BasicSettingStatusCode)', function (obj) {

        console.log(obj)
        //alert(obj.elem.checked);
        var statusCode = obj.elem.checked ? 0 : 1;

        ajaxutil.request({
            url: '/basicSetting/userinfo/updateStatus',
            data: {
                'operatorId': obj.elem.value,
                'statusCode': statusCode
            },
            success: function (res) {
                console.log(res)
                if (res.code == 200) {
                    dialog.alert.success(res.msg);
                } else {
                    dialog.alert.fail(res.msg);
                }
            }
        });

    })

    var loadData = function (param, pageIndex) {
        //执行重载
        table.reload('cn_GridBasicSetting', {
            page: {
                curr: pageIndex //刷新指定页
            }
            , where: param
        });
    }

    //筛选
    $('#btn_BasicSetting_Search').on('click', function () {
        loadData({
            operatorName: $('#txt_BasicIndex_OperatorName').val()
        }, 1)
    });

    //添加
    $('#btn_BasicSetting_Add').on('click', function () {
        clearForm();

        dialog.open({
            dialogId: 'dialog_BasicSetting_Add'
            , width: 450
            , height: 330
            , title: '添加用户'
            , ok: function (index) {
                addUser(index);
            }
            , cancel: function () {

            }
        });
    });

    var addUser = function (index) {
        var operatorNo = $(".cs_BasicSettingOperatorNo").val();
        var operatorName = $(".cs_BasicSettingOperatorName").val();
        var operatorPwd = $(".cs_BasicSettingOperatorPwd").val();

        ajaxutil.request({
            url: '/basicSetting/userInfo/add',
            data: {
                operatorNo: operatorNo
                , operatorName: operatorName
                , operatorPwd: operatorPwd
            },
            success: function (res) {
                if (res.code === 200) {
                    dialog.close(index);
                    dialog.alert.success('添加成功');

                    $('#txt_BasicIndex_OperatorName').val('');
                    //刷新页面
                    loadData({
                        operatorName: ''
                    }, 1)

                } else {
                    dialog.alert.fail(res.msg);
                }
            }
        });
    }

    var editUser = function (index, operatorId) {
        var operatorName = $(".cs_BasicSettingOperatorNameEdit").val();

        ajaxutil.request({
            url: '/basicSetting/userInfo/edit',
            data: {
                operatorId: operatorId
                , operatorName: operatorName
            },
            success: function (res) {
                if (res.code === 200) {
                    dialog.close(index);
                    dialog.alert.success('修改成功');

                    //当前页码（如果当前页存在多个表格，则需要换种写法）
                    var pageIndex = $(".layui-laypage-skip").find("input").val();

                    //刷新指定页面
                    loadData({
                        operatorName: $('#txt_BasicIndex_OperatorName').val()
                    }, pageIndex);
                } else {
                    dialog.alert.fail(res.msg);
                }
            }
        });
    }

    var resetPwd = function (index, operatorId) {
        var operatorPwd = $(".cs_BasicSettingNewOperatorPwd").val();
        var operatorPwdAgain = $(".cs_BasicSettingNewOperatorPwdAgain").val();

        ajaxutil.request({
            url: '/basicSetting/userInfo/resetpwd',
            data: {
                operatorId: operatorId
                , operatorPwd: operatorPwd
                , operatorPwdAgain: operatorPwdAgain
            },
            success: function (res) {
                if (res.code === 200) {
                    dialog.close(index);
                    dialog.alert.success('重置成功');

                    //当前页码（如果当前页存在多个表格，则需要换种写法）
                    var pageIndex = $(".layui-laypage-skip").find("input").val();

                    //刷新指定页面
                    loadData({
                        operatorName: $('#txt_BasicIndex_OperatorName').val()
                    }, pageIndex);
                } else {
                    dialog.alert.fail(res.msg);
                }
            }
        });
    }

    var getRoleInfo = function (operatorId) {
        ajaxutil.request({
            url: '/basicSetting/userInfo/getroleinfo',
            data: {
                operatorId: operatorId
            },
            success: function (res) {
                if (res.code === 200) {
                    console.log(res);
                    addUserRoleElement(res.data);
                } else {
                    dialog.alert.fail(res.msg);
                }
            }
        });
    }

    var allotRole = function (index, operatorId) {
        //获取选中角色id
        var roleIds = [];
        $("input:checkbox[name='role']:checked").each(function (i) {
            roleIds.push($(this).val());
        });

        ajaxutil.request({
            url: '/basicSetting/userInfo/allotrole',
            data: {
                operatorId: operatorId,
                roleIds: roleIds
            },
            success: function (res) {
                if (res.code === 200) {
                    dialog.close(index);
                    dialog.alert.success('分配角色成功');
                } else {
                    dialog.alert.fail(res.msg);
                }
            }
        });
    }

    var initEditForm = function (rowData) {
        $(".cs_BasicSettingOperatorNameEdit").val(rowData.operatorName);

        //更新 lay-filter="ft_BasicSettingForm" 所在容器内的全部表单状态
        form.render(null, 'ft_BasicSettingFormEdit');
    }

    ///清空表单
    var clearForm = function () {
        $(".cs_BasicSettingOperatorNo").val('');
        $(".cs_BasicSettingOperatorName").val('');
        $(".cs_BasicSettingOperatorPwd").val('');

        //更新 lay-filter="ft_BasicSettingForm" 所在容器内的全部表单状态
        form.render(null, 'ft_BasicSettingFormAdd');
    }

    //生成用户角色
    var addUserRoleElement = function (data) {
        $("#dialog_BasicSetting_AllotRole .cs_BasicSettingRoleCheckBox").empty();

        data.forEach(function (item, index) {
            var checked = item.checked == 1 ? 'checked' : '';
            var allotRoleHtml = '<input type="checkbox" value="' + item.roleId + '" name="role" lay-skin="primary" title="' + item.roleName + '" ' + checked + '>';

            $("#dialog_BasicSetting_AllotRole .cs_BasicSettingRoleCheckBox").append(allotRoleHtml);
        });

        form.render(null, 'ft_BasicSettingFormAllotRole');
    }
});